package book.test02;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.log4j.BasicConfigurator;

import java.io.IOException;

public class MRTest02 {
    public static class CountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        Text k = new Text();
        IntWritable v = new IntWritable(1);

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //分割每一行
            String[] data = value.toString().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
            //将城市和年限作为k
            k.set(data[5] + "," + data[4]);
            context.write(k, v);
        }
    }

    public static class CountReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
        Text k = new Text();
        IntWritable v = new IntWritable();

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            //每一组的数据数量就是职位需求量
            for (IntWritable value : values) {
                count += value.get();
            }
            //为了显示好看将”，“改为制表符
            k.set(key.toString().replace(",", "\t"));
            v.set(count);
            context.write(k, v);
        }
    }

        public static void main(String[] args) {
            BasicConfigurator.configure();
            Configuration conf = new Configuration();
            conf.set("fs.default", "hdfs://192.168.0.155:9000/");
            try {
                Job job = Job.getInstance(conf);

                job.setJarByClass(MRTest02.class);
                job.setMapperClass(CountMapper.class);
                job.setReducerClass(CountReduce.class);

                job.setMapOutputKeyClass(Text.class);
                job.setMapOutputValueClass(IntWritable.class);

                job.setOutputKeyClass(Text.class);
                job.setOutputValueClass(IntWritable.class);

                FileInputFormat.setInputPaths(job, "/MR/count/input");
                Path path = new Path("/MR/count/input");
                if (path.getFileSystem(conf).exists(path)) {
                    path.getFileSystem(conf).delete(path);
                }
                FileOutputFormat.setOutputPath(job, path);
                System.exit(job.waitForCompletion(true) ? 0 : 1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

